package com.dongnam.quanly.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import org.apache.commons.codec.binary.Base64;

/**
 * Basic symmetric encryption example
 */
public class CryptUtil {
	private static int ITERATIONS = 1024;
	private static final String password = "DFN#$WRIVBFOIEWQHqeoiruqwer23784fwjb";
	private static final String algothrim = "PBEWithMD5AndDES";
	private static final byte[] salt = new byte[] { (byte) 0x2c, (byte) 0x7a, (byte) 0x32, (byte) 0xf5, (byte) 0x08,
			(byte) 0xa9, (byte) 0xc0, (byte) 0xfe };

	public static String encrypt(String plaintext) throws Exception {
		// Create the PBEKeySpec with the given password
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());

		// Get a SecretKeyFactory for PBEWithSHAAndTwofish
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algothrim);

		// Create our key
		SecretKey key = keyFactory.generateSecret(keySpec);

		// Now create a parameter spec for our salt and iterations
		PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);

		// Create a cipher and initialize it for encrypting
		Cipher cipher = Cipher.getInstance(algothrim);
		cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

		byte[] ciphertext = cipher.doFinal(plaintext.getBytes());

		String saltString = Base64.encodeBase64String(salt);
		String ciphertextString = Base64.encodeBase64String(ciphertext);

		return saltString + ciphertextString;
	}

	public static String decrypt(String text) throws Exception {
		// Below we split the text into salt and text strings.
		String salt = text.substring(0, 12);
		String ciphertext = text.substring(12, text.length());

		byte[] saltArray = Base64.decodeBase64(salt);
		byte[] ciphertextArray = Base64.decodeBase64(ciphertext);

		// Create the PBEKeySpec with the given password
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());

		// Get a SecretKeyFactory for PBEWithSHAAndTwofish
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

		// Create our key
		SecretKey key = keyFactory.generateSecret(keySpec);

		// Now create a parameter spec for our salt and iterations
		PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray, ITERATIONS);

		// Create a cipher and initialize it for encrypting
		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

		// Perform the actual decryption
		byte[] plaintextArray = cipher.doFinal(ciphertextArray);

		return new String(plaintextArray);
	}

	public static boolean verify(String password, String encrypted) throws Exception {
		if (CryptUtil.encrypt(password).equals(encrypted)) {
			return true;
		}
		return false;
	}

	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md;
		md = MessageDigest.getInstance("MD5");
		byte[] md5hash = new byte[32];
		md.update(text.getBytes("iso-8859-1"), 0, text.length());
		md5hash = md.digest();
		return convertToHex(md5hash);
	}
}
